#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>

void writer(pid_t wfd)
{
    const char* str = "hello father, i am a child";
    char buffer[1024];

    int cnt = 0;
    pid_t id = getpid();
    while (1)
    {
        snprintf(buffer, sizeof(buffer), "%s, pid: %d, count: %d\n", str, id,  cnt++);
        write(wfd, buffer, strlen(buffer)-1); // 已经除去了字符串结束标志

        sleep(1);
    }
}


void reader(pid_t rfd)
{
    char buffer[1024];
    while (1)
    {
        read(rfd, buffer, sizeof(buffer));
        printf("I am father, this is a message: %s\n", buffer);
        
    }
}


int main()
{
    int pipefd[2];
    int n = pipe(pipefd); // pipefd[0] - r; pipefd[1] - w
    if (n == -1)
    {
        printf("pipe error\n");
        return -1;
    }
    printf("pipefd[0]: %d, pipefd[1]: %d\n", pipefd[0], pipefd[1]);

    pid_t id = fork();

    if (id == 0)
    {
        // child
        close(pipefd[0]); // w
        writer(pipefd[1]);

        exit(0);
    }

    // father
    close(pipefd[1]); // r
    reader(pipefd[0]);

    wait(NULL);

    return 0;
}